package com.mybatislearn.test;

import com.mybatislearn.mapper.UserMapper;
import com.mybatislearn.pojo.User;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

/**
 * @author wangzd
 * @create 2021-11-06 11:42
 */
public class SecondCache {

    private Configuration configuration;
    private SqlSessionFactory factory;

    @Before
    public void init(){
        SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
        factory = factoryBuilder.build(SecondCache.class.getResourceAsStream("/mybatis-config.xml"));
        configuration = factory.getConfiguration();
    }

    @Test
    public void cacheTest1(){
        Cache cache = configuration.getCache("com.mybatislearn.mapper.UserMapper");
        User user = new User(10L, "wangzd", 123456);
        cache.putObject("wangzd", user);
        cache.getObject("wangzd");
    }

    /**
     * 1.必须提交
     */
    @Test
    public void cacheTest2(){
        //1
        SqlSession session1 = factory.openSession(true);
        UserMapper mapper1 = session1.getMapper(UserMapper.class);
        User user1 = mapper1.queryNameById(1);
        System.out.println(user1);
        session1.commit();
        //2
        SqlSession session2 = factory.openSession(true);
        UserMapper mapper2 = session2.getMapper(UserMapper.class);
        User user2 = mapper2.queryNameById(1);
        System.out.println(user2);
    }

    @Test
    public void cacheTest3(){
        SqlSession session1 = factory.openSession(true);
        UserMapper mapper1 = session1.getMapper(UserMapper.class);
        User user1 = mapper1.queryNameById(1);
        System.out.println(session1);
        session1.commit();
    }
}
